package com.visionblue.business.ship.page.register.register

import androidx.lifecycle.viewModelScope
import com.visionblue.business.ship.base.BaseViewModel
import com.visionblue.business.ship.base.ViewState
import com.visionblue.business.ship.ext.SingleLiveEvent
import com.visionblue.business.ship.model.repository.DeviceInfoRepository
import com.visionblue.business.ship.util.toast
import kotlinx.coroutines.launch

/**
 * @author: xlh
 * @date: 2020-06-07 9:18 PM
 * @desc:
 */
class RegisterViewModel(
    private val registerRepository: RegisterRepository,
    private val deviceInfoRepository: DeviceInfoRepository
) : BaseViewModel() {

    val validateEvent = SingleLiveEvent<ViewState<Any>>()


    fun validatePinAndSnCode(pinCode: String, snCode: String) {
        if (pinCode.isEmpty()) {
            toast { "请输入PIN码" }
            return
        }

        if (snCode.isEmpty()) {
            toast { "请输入sn码" }
            return
        }

        viewModelScope.launch {
            checkState(
                validateEvent,
                registerRepository.validatePinAndSnCode(pinCode, snCode),
                successAction = { data, isLoadMore ->
                    deviceInfoRepository.pin = pinCode
                    deviceInfoRepository.sn = snCode

                    validateEvent.value =
                        ViewState(data = data, isSuccess = true, isLoadMore = isLoadMore)
                })
        }
    }

    fun getSnAndPinCode(): Pair<String, String> {
        return Pair(deviceInfoRepository.sn, deviceInfoRepository.pin)
    }

    fun isEdit(pinText: String, snText: String): Boolean {
        return deviceInfoRepository.sn != snText || deviceInfoRepository.pin != pinText
    }

}